package stream;

import org.junit.Test;

import java.util.Comparator;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CollectorsTest {

    @Test
    public void maxMin() {

        Optional<String> collect = Stream.of("tu", "you")
//                .collect(Collectors.maxBy(Comparator.comparingInt(String::length)));
                .collect(Collectors.minBy(Comparator.comparingInt(String::length)));
        collect.ifPresent(System.out::println);
    }

    @Test
    public void sum() {
        Integer collect = Stream.of(1, 2, 3).collect(Collectors.summingInt(Integer::intValue));
        System.out.println(collect);
    }

    @Test
    public void average() {
        Double collect = Stream.of(1, 2, 3).collect(Collectors.averagingInt(Integer::intValue));
        System.out.println(collect);
    }

    @Test
    public void join() {
        System.out.println(Stream.of("tu", "you").collect(Collectors.joining()));
        System.out.println(Stream.of("tu", "you").collect(Collectors.joining(",")));
        System.out.println(Stream.of("tu", "you").collect(Collectors.joining(",", "(", ")")));
    }

    @Test
    public void groupBy() {
        Stream.of("tu", "you", "you")
                .collect(Collectors.groupingBy(String::toString))
                .forEach((k, v) -> System.out.println(k + ":" + v));
    }

    /**
     * 分组统计
     */
    @Test
    public void groupBy2() {
        Stream.of("tu", "you", "you")
                .collect(Collectors.groupingBy(String::toString, Collectors.counting()))
                .forEach((k, v) -> System.out.println(k + ":" + v));
    }
}
